package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.BaseContext;
import com.demo.common.CustomException;
import com.demo.common.R;
import com.demo.dao.OrdersDao;
import com.demo.domain.*;
import com.demo.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrdersDao ordersDao;


    @Override
    @Transactional
    public R<String> submit(@RequestBody Orders orders) {

        //获取用户id
        Long currentId = BaseContext.getCurrentId();

        //获取购物车信息
        LambdaQueryWrapper<ShoppingCart> shoppingCart = new LambdaQueryWrapper<>();
        shoppingCart.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCart);

        //判断购物车信息知否为空
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，无法下单");
        }

        //获取用户信息
        User user = userService.getById(currentId);

        //获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("用户地址信息错误，无法下单");
        }

        //生成订单号
        long orderId = IdWorker.getId();

        //生成总金额
        AtomicInteger amount = new AtomicInteger(0);


        orders.setNumber(String.valueOf(orderId));
        orders.setUserId(currentId);
        orders.setAddressBookId(orders.getAddressBookId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(orders.getPayMethod());
        orders.setRemark(orders.getRemark());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //保存信息至orders表中
        this.save(orders);

        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            return orderDetail;
        }).collect(Collectors.toList());

        //保存信息至orderDetail表中,多条数据
        orderDetailService.saveBatch(orderDetailList);

        //删除购物车信息
        shoppingCartService.remove(shoppingCart);

        return R.success("下单成功");
    }

    @Override
    public R<Page> userPage(Page<Orders> pageInfo) {
        return this.ordersDao.userPage(pageInfo);
    }

}

